
import { _decorator,Node,Rect,Vec2,Graphics} from 'cc';

import {GameConfig} from "./GameConfig";
import {Ball} from "./Ball";


export class Grid
{
    public x:number=0;
    public y:number=0;
    public gridIdx:number=0;

    //grid的坐标范围
    public rect:Rect=new Rect(0,0,0,0);

    public node:Node=null;

    public ball:Ball=null;

    constructor(xPos:number, yPos:number)
    {
        this.x=xPos;
        this.y=yPos;
        this.gridIdx=yPos*GameConfig.HorizontalGridsNum + xPos;
        this.initRect();
    }

    public initRect(gridWidth:number=GameConfig.GridWidth)
    {
        let startX:number= -2.5 * gridWidth - 2.5* GameConfig.GridInterval;

        this.rect.x=startX + this.x*(gridWidth+GameConfig.GridInterval) - 0.5* gridWidth;
        this.rect.y= -this.y * (gridWidth+GameConfig.GridInterval) - 0.5* gridWidth;
        this.rect.width=gridWidth;
        this.rect.height=gridWidth;
    }

    public setGridIdx(idx:number)
    {
        this.gridIdx=idx;
    }

    public setNode(node:Node)
    {
        this.node=node;

        /*
        let graphics:Graphics=this.node.getComponent(Graphics);
        graphics.rect(this.rect.x, this.rect.y, this.rect.width, this.rect.height);
        graphics.stroke();*/
    }

    public setBall(ball:Ball)
    {
        this.ball=ball;
    }

    public isInRect(p:Vec2):boolean
    {
        return this.rect.contains(p);
    }

    public onPressed()
    {
        //console.log("** grid on pressed i="+this.gridIdx);
        if(this.ball!==null)
            this.ball.onPressed();
    }

    public onConnect()
    {
        if(this.ball!==null)
            this.ball.onConnect();
    }

    public onRelease()
    {
        if(this.ball!==null)
            this.ball.onRelease();
    }
}

